package com.kfm.ajax.controller;

import com.kfm.ajax.model.UserModel;
import com.kfm.ajax.model.UserModelDTO;
import com.kfm.ajax.model.UserModelVO;
import com.kfm.ajax.model.valid.LoginGroup;
import com.kfm.ajax.service.MenuService;
import com.kfm.ajax.service.UserModelService;
import com.kfm.ajax.service.exception.ServiceException;
import com.kfm.ajax.util.Constant;
import com.kfm.ajax.util.Resp;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    private UserModelService userModelService;
    @Autowired
    private MenuService menuService;

    @GetMapping({"/", "/login"})
    public ModelAndView login(ModelAndView modelAndView) {
//        ModelAndView modelAndView = new ModelAndView("login");
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        // 生成的验证码
        String text = specCaptcha.text();

        request.getSession().setAttribute(Constant.CAPTCHA, text);

        specCaptcha.out(response.getOutputStream());
    }

    @PostMapping("/login")
    public Resp doLogin(@Validated(LoginGroup.class) @RequestBody UserModelVO userModel
                            , BindingResult br
                            , @SessionAttribute(value = Constant.CAPTCHA, required = false) String sessionCaptcha
                            , HttpSession httpSession) {
        boolean flag = true;
        Map<String, String> errorMessage = new HashMap<>();
        // 手动校验验证码
        if (!StringUtils.hasText(userModel.getCaptcha()) || !userModel.getCaptcha().equalsIgnoreCase(sessionCaptcha)) {
            flag = false;
            httpSession.removeAttribute(Constant.CAPTCHA);
            errorMessage.put("captcha", "验证码错误");
        }
        if (br.hasErrors()){
            flag = false;
            error(errorMessage, br);
        }

        if (flag){
            // 参数校验 ok
            UserModel model;
            try {
                if ( (model = userModelService.login(userModel)) != null){
                    // 登录成功
                    model.setPassword(null);
                    httpSession.setAttribute(Constant.LOGIN_USER, model);
                    return Resp.ok("index");
                } else {
                    return Resp.error(501, "用户名或密码错误", null);
                }
            } catch (ServiceException e) {
                e.printStackTrace();
                return Resp.error(502, e.getMessage(), null);
            }
        } else {
            // 参数校验失败
            return Resp.error("参数校验失败", errorMessage);
        }
    }

    @GetMapping("/index")
    public ModelAndView index(@SessionAttribute(Constant.LOGIN_USER)UserModelDTO userModelDTO){
        ModelAndView mv = new ModelAndView("index");

        mv.addObject("menus", userModelDTO.getMenuModelList());
        return mv;
    }

    @GetMapping("/403")
    public ModelAndView error403(){
        ModelAndView mv = new ModelAndView("403");
        return mv;
    }

    private void error(Map<String, String> map, BindingResult br) {
        List<FieldError> fieldErrors = br.getFieldErrors();

        for (FieldError fieldError : fieldErrors){
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
    }
}
